package io.api.modules.project.controller;

import com.google.common.collect.ImmutableBiMap;
import io.admin.common.constant.Constant;
import io.admin.common.page.PageData;
import io.admin.common.utils.Result;
import io.admin.common.validator.ValidatorUtils;
import io.admin.common.validator.group.AddGroup;
import io.admin.common.validator.group.DefaultGroup;
import io.admin.common.validator.group.UpdateGroup;
import io.api.annotation.LoginUser;
import io.api.modules.login.dto.WorkOrderDTO;
import io.api.modules.login.entity.UserEntity;
import io.api.modules.project.dto.MessageDTO;
import io.api.modules.project.entity.MessageEntity;
import io.api.modules.project.entity.MessageUserEntity;
import io.api.modules.project.service.MessageService;
import io.api.modules.project.service.MessageUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 用户消息表
 *
 * @author Mark sunlightcs@gmail.com
 * @since 1.0.0 2024-07-17
 */
@RestController
@RequestMapping("/api/message")
@Api(tags="用户消息表")
public class MessageController {
    @Autowired
    private MessageService messageService;

    @Autowired
    private MessageUserService messageUserService;

    @GetMapping("page")
    @ApiOperation("分页")
    @ApiImplicitParams({
        @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType="int") ,
        @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query",required = true, dataType="int") ,
        @ApiImplicitParam(name = Constant.ORDER_FIELD, value = "排序字段", paramType = "query", dataType="String") ,
        @ApiImplicitParam(name = Constant.ORDER, value = "排序方式，可选值(asc、desc)", paramType = "query", dataType="String")
    })
    public Result<PageData<MessageDTO>> page(@ApiIgnore @RequestParam Map<String, Object> params, @LoginUser UserEntity user){
        params.put("userId", user.getId());
        PageData<MessageDTO> page = messageService.page(params);
        return new Result<PageData<MessageDTO>>().ok(page);
    }

    @GetMapping("count")
    @ApiOperation("统计未读数")
    public Result count(@LoginUser UserEntity user) {
        long count = messageService.countUnRead(user.getId());
        return new Result().ok(ImmutableBiMap.of("msgCount", count));
    }

    @PutMapping("readAll")
    @ApiOperation("全部已读")
    public Result readAll(@LoginUser UserEntity user) {
        List<Long> ids = messageService.selectUnRead(user.getId()).stream()
                .map(MessageEntity::getId).collect(Collectors.toList());
        List<MessageUserEntity> entities = ids.stream().map(msgId -> {
            MessageUserEntity dto = new MessageUserEntity();
            dto.setMessageId(msgId);
            dto.setUserId(user.getId());
            return dto;
        }).collect(Collectors.toList());
        messageUserService.insertBatch(entities);
        return new Result();
    }

    @PutMapping("read")
    @ApiOperation("部分已读")
    public Result read(@RequestParam Long[] ids, @LoginUser UserEntity user) {
        List<MessageUserEntity> entities = Arrays.stream(ids).map(msgId -> {
            MessageUserEntity dto = new MessageUserEntity();
            dto.setMessageId(msgId);
            dto.setUserId(user.getId());
            return dto;
        }).collect(Collectors.toList());
        messageUserService.insertBatch(entities);
        return new Result();
    }

    @GetMapping("{id}")
    @ApiOperation("信息")
    public Result<MessageDTO> get(@PathVariable("id") Long id){
        MessageDTO data = messageService.get(id);

        return new Result<MessageDTO>().ok(data);
    }

    @PostMapping("worksOrder")
    @ApiOperation("保存")
    public Result worksOrder(@RequestBody WorkOrderDTO workOrderDTO, @LoginUser UserEntity user){
        ValidatorUtils.validateEntity(workOrderDTO);
        messageService.saveBatch(workOrderDTO, user);
        return new Result();
    }

    @PostMapping
    @ApiOperation("保存")
    public Result save(@RequestBody MessageDTO dto, @LoginUser UserEntity user){
        //效验数据
        ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);
        dto.setMsgType(1);
        dto.setCreateDate(new Date());
        dto.setAdminUserId(user.getId());
        dto.setAdminUserName(user.getUsername());
        messageService.save(dto);
        return new Result();
    }

    @PutMapping
    @ApiOperation("修改")
    public Result update(@RequestBody MessageDTO dto, @LoginUser UserEntity user){
        //效验数据
        ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);
        dto.setMsgType(1);
        dto.setAdminUserId(user.getId());
        dto.setAdminUserName(user.getUsername());
        messageService.update(dto);
        return new Result();
    }

}